package com.lingkang.sales.config.auth;

import com.lingkang.sales.data.domain.SecUser;
import com.lingkang.sales.data.entity.SaCompany;
import com.lingkang.sales.data.entity.SaRole;
import com.lingkang.sales.data.entity.SaUser;
import com.lingkang.sales.service.AuthService;
import com.lingkang.sales.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author linke
 * @date 2020/5/23 18:31
 * @description 自定义用户登录
 */
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;
  @Autowired
  private AuthService authService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (StringUtils.isEmpty(username)) {
      throw new UsernameNotFoundException(null);
    }
    SaUser user = userService.get(username);
    if (user == null) {
      throw new UsernameNotFoundException("账号不存在！");
    }
    if (user.getEnabled() == 0) {
      throw new RuntimeException("账号无效");
    }
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    List<SaRole> roles = authService.getRoles(user.getUsername());
    roles.forEach(r -> {
      //security的验证规则需要ROLE_
      grantedAuthorities.add(new SimpleGrantedAuthority(r.getRoleName()));
    });

    //使用自定义SecUser，，可以添加更多信息
    SecUser secUser = new SecUser(user.getUsername(), user.getPassword(), grantedAuthorities);
    secUser.setUsername(username);
    secUser.setNickname(user.getNickname());
    secUser.setSex(user.getSex());

    //机构信息
    SaCompany company = userService.getCompany(user.getComCode());
    if (company != null) {
      secUser.setComCode(user.getComCode());
      secUser.setComLevel(company.getLevel());
      secUser.setComName(company.getUpperAddress().replaceAll(",", "") + "公司");
      secUser.setUpdateCode(company.getUpperCode());
      secUser.setProvinceCode(company.getUpperCode().split(",")[1]);
    }
    return secUser;
  }
}
